package com.wing.productionPlan.controller.admin;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.alibaba.nacos.common.utils.CollectionUtils;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wing.common.exception.BusinessException;
import com.wing.productionPlan.model.request.ProductionProcessMaterialForm;
import com.wing.productionPlan.model.response.ProductionProcessMaterialVO;
import com.wing.productionPlan.model.response.SimpleWorkOrderProcessVO;
import com.wing.productionPlan.model.response.SimpleWorkOrderVO;
import com.wing.productionPlan.utils.ExcelUtils;
import com.wing.web.annotation.RequestObjectFieldIgnore;
import com.wing.common.utils.JsonResult;
import com.wing.common.utils.PageResult;
import com.wing.productionPlan.model.entity.SimpleWorkOrder;
import com.wing.productionPlan.model.request.SimpleWorkOrderForm;
import com.wing.productionPlan.service.SimpleWorkOrderService;
import com.wing.web.excel.DeviceExcelIn;
import com.wing.web.excel.DownExcelUtil;
import com.wing.web.excel.ExcelUtil;
import com.wing.web.excel.WorkOrderExcelIn;
import com.wing.web.utils.JwtUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.hibernate.validator.constraints.EAN;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

/**
 *
 * @author
 */
@Slf4j
@Validated
@Api(value = "Admin-简版工单表管理", tags = "#/productionPlan/simpleWorkOrder")
@RestController("simpleWorkOrderController")
@RequestMapping("productionPlan/admin/simpleWorkOrder")
@RequiredArgsConstructor
public class SimpleWorkOrderController {

    private final SimpleWorkOrderService simpleWorkOrderService;


    @ApiOperation(value = "查询所有简版工单表", notes = "搜索")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "第几页", defaultValue = "1", example = "1", dataType = "Integer", paramType = "query")
            ,@ApiImplicitParam(name = "limit", value = "每页多少条", defaultValue = "10", example = "10", dataType = "Integer", paramType = "query")
            ,@ApiImplicitParam(name = "sort", value="排序字段名", defaultValue = "create_time", example = "create_time", dataType = "String", paramType = "query")
            ,@ApiImplicitParam(name = "order", value="排序规则(asc:正序, desc:倒序)", defaultValue = "asc", example = "asc", dataType = "String", paramType = "query")
            ,@ApiImplicitParam(name = "skuCode", value="产品sku编号", dataType = "String", paramType = "query")
            ,@ApiImplicitParam(name = "code", value="工单编号", dataType = "String", paramType = "query")
    })
    @GetMapping("/list")
    public PageResult<SimpleWorkOrderVO> list(
            @RequestParam(defaultValue = "1") Integer page
            ,@RequestParam(defaultValue = "10") Integer limit
            ,@RequestParam(defaultValue = "create_time") String sort
            ,@RequestParam(defaultValue = "asc") String order
            ,String skuCode
            ,String code
            ,String workPlanCode
            ,Long processId
            ,String startTime
            ,String endTime
            //,String materialSkuCode
            ,SimpleWorkOrder.Status status
            ,String inStatus
    ){

        Page<SimpleWorkOrderVO> pg = new Page<>(page, limit);
        Map<String, Object> params = new HashMap<>();
        //查询未完成的
//        params.put("enterpriseCode", JwtUtils.getEnterpriseCode());
        //搜索
        if(StringUtils.isNotBlank(skuCode)){
            params.put("skuCode",skuCode);
        }
        if(StringUtils.isNotBlank(code)){
            params.put("code",code);
        }
        if(StringUtils.isNotBlank(skuCode)){
            params.put("workPlanCode",workPlanCode);
        }
        if(processId != null){
            params.put("processId",processId);
        }
        params.put("startCreateTime",startTime);
        params.put("endCreateTime",endTime);
        /*if(StringUtils.isNotBlank(materialSkuCode)){
            params.put("materialSkuCode",materialSkuCode);
        }*/
        if(status!=null){
            params.put("status",status.getValue());
        }
        if(StringUtils.isNotBlank(inStatus)){
            params.put("inStatus", inStatus);
        }
        Page<SimpleWorkOrderVO> list = simpleWorkOrderService.pageList4app(pg, params);
        return new PageResult<>(list.getRecords(), list.getTotal());
    }



    @ApiOperation(value = "添加简版工单表", notes = "添加")
    @RequestObjectFieldIgnore({"id", "createTime", "remark"})
    @PostMapping("/add")
    public JsonResult add(@Validated(SimpleWorkOrderForm.Add.class) SimpleWorkOrderForm simpleWorkOrderForm) {
        if (simpleWorkOrderService.add(simpleWorkOrderForm) > 0) {
            return JsonResult.success("添加成功");
        }
        return JsonResult.fail("添加失败");
    }




    @ApiOperation(value = "修改简版工单表", notes = "修改")
    @PutMapping("/update")
    public JsonResult update(@Validated(SimpleWorkOrderForm.Update.class) SimpleWorkOrderForm simpleWorkOrderForm) {
        SimpleWorkOrder simpleWorkOrder = simpleWorkOrderService.getById(simpleWorkOrderForm.getId());
        if(simpleWorkOrder == null){
        return JsonResult.fail("修改失败！");
        }
        CopyOptions copyOptions = CopyOptions.create()
        .setEditable(SimpleWorkOrder.class)
        .setIgnoreError(true)
        .setIgnoreNullValue(true);
        BeanUtil.copyProperties(simpleWorkOrderForm, simpleWorkOrder, copyOptions);
        if (simpleWorkOrderService.updateById(simpleWorkOrder)) {
            return JsonResult.success("修改成功！");
        }
        return JsonResult.fail("修改失败！");
    }



    @ApiOperation(value = "删除简版工单表", notes = "删除")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "simpleWorkOrderId", value = "简版工单表id", required = true, dataType = "Integer", paramType = "path")
    })
    @DeleteMapping("/{id}" )
    public JsonResult delete(@PathVariable("id") Long simpleWorkOrderId) {
        if (simpleWorkOrderService.removeById(simpleWorkOrderId)) {
            return JsonResult.success("删除成功");
        }
        return JsonResult.fail("删除失败");
    }
    @ApiOperation(value = "添加工单", notes = "删除")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "simpleWorkOrderForm", value = "插入的数据", required = true, dataType = "list", paramType = "path")
    })
    @PostMapping("/addSimpleWorkOrder")
    public JsonResult addSimpleWorkOrder(@RequestBody SimpleWorkOrderForm simpleWorkOrderForm) {
        try {
            simpleWorkOrderService.addNewSimpleWorkOrder(simpleWorkOrderForm);
            return JsonResult.success("操作成功");
        }catch (Exception e){
            log.error("简版工单添加接口异常，原因是：{} ", e.getMessage(), e);
            return JsonResult.fail("操作失败:" + e.getMessage());
        }
    }
    @ApiOperation(value = "查询工单详情", notes = "删除")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "工单id", required = true, dataType = "list", paramType = "path")
    })
    @GetMapping("/getSimpleWorkOrderVODetails")
    public JsonResult<SimpleWorkOrderVO> getSimpleWorkOrderVODetails(Long id){
        SimpleWorkOrderVO workOrderVO = simpleWorkOrderService.getSimpleWorkOrderVODetails(id);
        return JsonResult.success(workOrderVO);
    }

    @ApiOperation(value = "查询工单详情工序下的设备和物料", notes = "查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "processId", value = "工序id", required = true, dataType = "list", paramType = "path")
            ,@ApiImplicitParam(name = "workOrderId", value = "工单id", required = true, dataType = "list", paramType = "path")
    })
    @GetMapping("/getWorkOrderDeviceAndMaterial")
    public JsonResult<SimpleWorkOrderProcessVO> getWorkOrderDeviceAndMaterial(Long processId,Long workOrderId){
        SimpleWorkOrderProcessVO simpleWorkOrderProcessVO = simpleWorkOrderService.getWorkOrderDeviceAndMaterial(processId,workOrderId);
        return JsonResult.success(simpleWorkOrderProcessVO);
    }

    @ApiOperation(value = "作废工单下的工序", notes = "修改")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "工序id", required = true, dataType = "Long", paramType = "path")
    })
    @PutMapping("/cancellationWorkOrderProcess")
    public JsonResult cancellationWorkOrderProcess(Long id){
        try {
            simpleWorkOrderService.cancellationWorkOrderProcess(id);
            return JsonResult.success("操作成功");
        }catch (Exception e){
            log.error("作废工序接口异常，原因是：{} ", e.getMessage(), e);
            return JsonResult.fail("操作失败:" + e.getMessage());
        }
    }
    @ApiOperation(value = "作废工单下的设备", notes = "修改")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "设备id", required = true, dataType = "Long", paramType = "path")
    })
    @PutMapping("/cancellationWorkOrderDevice")
    public JsonResult cancellationWorkOrderDevice(Long id){
        try {
            simpleWorkOrderService.cancellationWorkOrderDevice(id);
            return JsonResult.success("操作成功");
        }catch (Exception e){
            log.error("作废工单下的设备接口异常，原因是：{} ", e.getMessage(), e);
            return JsonResult.fail("操作失败:" + e.getMessage());
        }
    }
    @ApiOperation(value = "作废工单下的物料", notes = "修改")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "物料id", required = true, dataType = "Long", paramType = "path")
    })
    @PutMapping("/cancellationWorkOrderMaterial")
    public JsonResult cancellationWorkOrderMaterial(Long id){
        try {
            simpleWorkOrderService.cancellationWorkOrderMaterial(id);
            return JsonResult.success("操作成功");
        }catch (Exception e){
            log.error("作废工单下的物料接口异常，原因是：{} ", e.getMessage(), e);
            return JsonResult.fail("操作失败:" + e.getMessage());
        }
    }

    @ApiOperation(value = "修改简版工单表", notes = "修改")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "simpleWorkOrderForm", value = "插入的数据", required = true, dataType = "list", paramType = "path")
    })
    @PutMapping("/updateWorkOrder")
    public JsonResult updateWorkOrder(@RequestBody SimpleWorkOrderForm simpleWorkOrderForm) {
        try {
            simpleWorkOrderService.updateWorkOrder(simpleWorkOrderForm);
            return JsonResult.success("操作成功");
        }catch (Exception e){
            log.error("简版工单修改接口异常，原因是：{} ", e.getMessage(), e);
            return JsonResult.fail("操作失败:" + e.getMessage());
        }
    }
    @ApiOperation(value = "查询历史工单的物料已经计算预估数量", notes = "修改")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "skuCode", value = "生产产品编号", required = true, dataType = "string", paramType = "path")
            ,@ApiImplicitParam(name = "productionQuantity", value = "生产数量", required = true, dataType = "Int", paramType = "path")
    })
    @GetMapping("/getMaterialForecastData")
    public JsonResult<List<SimpleWorkOrderProcessVO>> getMaterialForecastData(@RequestParam(value = "skuCode")String skuCode
            ,@RequestParam(value = "productionQuantity")Integer productionQuantity
            ){
        return simpleWorkOrderService.getMaterialForecastData(skuCode,productionQuantity);
    }
    /**
     * 下载简版工单录入excel模板
     */
    @ApiOperation(value = "下载简版工单录入excel模板")
    @GetMapping("/template")
    public void template(HttpServletResponse response, HttpServletRequest request) throws IOException {
        String[] headerArr = {"工单编号(*)"};
        //String[] indexArr = {"2","3","6","7","8"};
        List<String[]> downData = new ArrayList<>();
        DownExcelUtil.createExcelTemplate(response, request, "简版工单导入模板", Arrays.asList(headerArr),downData, null);
    }
    /**
     * 导入excel
     */
    @ApiOperation(value = "导入excel")
    @PostMapping("/importExcel")
    public JsonResult importExcel(HttpServletRequest request, @RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return JsonResult.fail("导入文件为空！");
        }
        try {
            //获取原始的文件名
            String originalFilename = file.getOriginalFilename();
            String fileType = originalFilename.substring(originalFilename.lastIndexOf(".") + 1, originalFilename.length());
            ExcelUtil<WorkOrderExcelIn> reader = new ExcelUtil<>();
            InputStream is = file.getInputStream();
            List<WorkOrderExcelIn> list = reader.read(is, WorkOrderExcelIn.class);
            if (CollectionUtils.isEmpty(list)) {
                return JsonResult.fail("请在表格中添加数据！");
            }
            simpleWorkOrderService.importExcel(list);
        } catch (BusinessException e) {
            log.error("导入文件异常！异常信息:", e);
            return JsonResult.fail(e.getCode(), e.getMessage());
        } catch (Exception e) {
            //e.printStackTrace();
            log.error("导入文件异常！异常信息:", e);
            return JsonResult.exception("导入文件异常！异常信息:" + e.getMessage());
        }
        return JsonResult.success("导入成功！");
    }
    @ApiOperation(value = "工单导出")
    @GetMapping("/export")
    public void export(HttpServletResponse response, String startCreateTime, String endCreateTime, String enterpriseCode){
        List<SimpleWorkOrderVO> list = new ArrayList<>();
        if ("".equals(startCreateTime) || "".equals(endCreateTime)){
            log.error("创建时间为空："+startCreateTime);
        }
        endCreateTime = endCreateTime+" 23:59:59";
        Map paramsMap = new HashMap();
        paramsMap.put("startCreateTime",startCreateTime);
        paramsMap.put("endCreateTime",endCreateTime);
        paramsMap.put("enterpriseCode",enterpriseCode);
        list = simpleWorkOrderService.list4app(paramsMap);
        ExcelUtils.export(response,"基础工单列表",list, SimpleWorkOrderVO.class);
    }

    @ApiOperation(value = "作废")
    @PutMapping("/cancel/{id}")
    public JsonResult cancel(@PathVariable("id") Long id){
        return  simpleWorkOrderService.cancel(id);
    }
}
